"""
DAQ设备TCP连接测试程序 - Python版本
根据C版本的tcp_demo调用流程，使用Python绑定模块实现各设备的测试函数
"""

import time, os
from python_bind.tcp_server_binding import TCPServerBinding
from python_bind.daq125_binding import DAQ125Binding
from python_bind.daq206_binding import DAQ206Binding
from python_bind.daq207_binding import DAQ207Binding
from python_bind.daq216_binding import DAQ216Binding
from python_bind.daq217_binding import DAQ217Binding
from python_bind.daq322_binding import DAQ322Binding
from python_bind.base_device_binding import (
    LockzhinerADCVoltage,
    LockzhinerADCSampleRate,
    LockzhinerADCChannel,
    LockzhinerADCTriggerType,
    LockzhinerADCTriggerMode
)

# DLL文件路径（需要根据实际情况修改）
# 获取当前文件的绝对路径

current_dir = os.path.dirname(os.path.abspath(__file__))
import platform
if platform.system() == "Windows":
    DLL_PATH = os.path.join(current_dir, "libdaq-4.0.0.dll")
else:
    DLL_PATH = os.path.join(current_dir, "liblibdaq-3.10.4.so")


# 设备配置常量
class DeviceConfig:
    # 触发类型
    TRIGGER_TYPE_DOUBLE_EDGE = LockzhinerADCTriggerType.DoubleEdge
    
    # 触发模式
    TRIGGER_MODE_COMMON = LockzhinerADCTriggerMode.Common
    
    # 触发通道
    TRIGGER_CHANNEL_NONE = LockzhinerADCChannel.ADCChannelAINNone
    
    # 触发电平
    TRIGGER_LEVEL = 100  # 100mV
    
    # 采样率
    SAMPLE_RATE_500K = LockzhinerADCSampleRate.ADCSampleRate_500_K
    
    # 电压范围
    VOLTAGE_10V = LockzhinerADCVoltage.ADCVoltage_10_V
    
    # 采集长度
    TRIGGER_LENGTH = 4920
    
    # 网络配置
    IP_ADDRESS = "192.168.1.100"
    PORT = 8899

def test_daq206():
    """测试DAQ206设备"""
    print("开始测试DAQ206设备")
    
    # 创建TCP服务器
    tcp_server = TCPServerBinding(DLL_PATH)
    server_handle = tcp_server.create_server(DeviceConfig.IP_ADDRESS, DeviceConfig.PORT)
    if not server_handle:
        print("创建TCP服务器失败")
        return False
    
    try:
        # 开始接受连接
        tcp_server.start_accept(server_handle, 10000, True, 1)
        
        # 等待连接完成
        while not tcp_server.is_accept_complete(server_handle):
            time.sleep(0.1)
        
        # 获取客户端列表
        client_ips = tcp_server.get_clients_ip(server_handle)
        print(f"获取到客户端列表，数量: {len(client_ips)}")
        
        for i, ip in enumerate(client_ips):
            print(f"客户端 {i} IP: {ip}")
        
        if not client_ips:
            print("没有获取到客户端")
            return False
        
        # 获取客户端句柄
        client_handle = tcp_server.get_client(server_handle, client_ips[0])
        if not client_handle:
            print("获取客户端句柄失败")
            return False
        
        print("成功获取客户端句柄")
        
        # 创建DAQ206设备
        daq206 = DAQ206Binding(DLL_PATH)
        device_handle = daq206.create_device()
        if not device_handle:
            print("创建DAQ206设备失败")
            return False
        
        try:
            # 使用后端
            if not daq206.use_backend(device_handle, client_handle):
                print("设置设备后端失败")
                return False
            
            # 初始化设备
            if not daq206.initialize_device(device_handle):
                print("初始化设备失败")
                return False
            
            # 连接设备
            if not daq206.connect_device(device_handle):
                print("连接设备失败")
                return False
            time.sleep(1)
            
            # 配置ADC触发 - 双边沿触发 普通触发 触发电平100mV
            if not daq206.config_adc_trigger(device_handle, 
                                            DeviceConfig.TRIGGER_TYPE_DOUBLE_EDGE,
                                            DeviceConfig.TRIGGER_MODE_COMMON,
                                            DeviceConfig.TRIGGER_CHANNEL_NONE,
                                            DeviceConfig.TRIGGER_LEVEL):
                print("配置触发失败")
                return False
            
            # 设置采样率500k
            if not daq206.config_adc_sample_rate(device_handle, DeviceConfig.SAMPLE_RATE_500K):
                print("配置采样率失败")
                return False
            
            # 电压范围±10V
            if not daq206.config_adc_voltage(device_handle, DeviceConfig.VOLTAGE_10V):
                print("配置电压范围失败")
                return False
            
            # 设置开启2通道 (DAQ206是2通道设备)
            channel_mask = 0x03  # 0b00000011
            if not daq206.config_adc_channel(device_handle, channel_mask):
                print("配置ADC通道失败")
                return False
            
            # 设置采集长度4920
            if not daq206.config_adc_trigger_length(device_handle, DeviceConfig.TRIGGER_LENGTH):
                print("配置触发长度失败")
                return False
            
            # 设置全通道DC (1代表DC，0代表AC)
            acdc_channel = 0x03  # 全通道DC
            if not daq206.config_acdc(device_handle, acdc_channel):
                print("配置ACDC失败")
                return False
            
            # 停止上次采集
            if not daq206.stop_collection(device_handle):
                print("停止采集失败")
                return False
            
            # 等待3秒
            time.sleep(3.0)
            
            # 开始采集
            if not daq206.start_collection(device_handle):
                print("开始采集失败")
                return False
            
            # 等待3秒
            time.sleep(3.0)
            
            # 软件触发
            if not daq206.config_adc_trigger_source(device_handle):
                print("配置触发源失败")
                return False
            
            # 读取数据
            channel_count = daq206.get_adc_legal_channel_size(device_handle)
            for channel in range(channel_count):
                while True:
                    success, data = daq206.try_read_data_batch(device_handle, channel,
                                                             DeviceConfig.TRIGGER_LENGTH)
                    if not success:
                        continue
                    
                    print(f"成功从通道 {channel + 1} 读取 {len(data)} 个数据点")
                    if data:
                        print(f"通道 {channel + 1} 前10个值: {data[:10]}")
                    break
            
            # 停止采集
            if not daq206.stop_collection(device_handle):
                print("停止采集失败")
                return False
            
            # 断开设备连接
            if not daq206.disconnect_device(device_handle):
                print("断开设备连接失败")
                return False
            
            print("DAQ206测试成功完成")
            return True
            
        finally:
            # 清理设备资源
            daq206.delete_device(device_handle)
    
    finally:
        # 清理TCP服务器资源
        tcp_server.delete_server(server_handle)

def test_daq207():
    """测试DAQ207设备"""
    print("开始测试DAQ207设备")
    
    # 创建TCP服务器
    tcp_server = TCPServerBinding(DLL_PATH)
    server_handle = tcp_server.create_server(DeviceConfig.IP_ADDRESS, DeviceConfig.PORT)
    if not server_handle:
        print("创建TCP服务器失败")
        return False
    
    try:
        # 开始接受连接
        tcp_server.start_accept(server_handle, 10000, True, 1)
        
        # 等待连接完成
        while not tcp_server.is_accept_complete(server_handle):
            time.sleep(0.1)
        
        # 获取客户端列表
        client_ips = tcp_server.get_clients_ip(server_handle)
        print(f"获取到客户端列表，数量: {len(client_ips)}")
        
        if not client_ips:
            print("没有获取到客户端")
            return False
        
        # 获取客户端句柄
        client_handle = tcp_server.get_client(server_handle, client_ips[0])
        if not client_handle:
            print("获取客户端句柄失败")
            return False
        
        # 创建DAQ207设备
        daq207 = DAQ207Binding(DLL_PATH)
        device_handle = daq207.create_device()
        if not device_handle:
            print("创建DAQ207设备失败")
            return False
        
        try:
            # 使用后端
            if not daq207.use_backend(device_handle, client_handle):
                print("设置设备后端失败")
                return False
            
            # 初始化设备
            if not daq207.initialize_device(device_handle):
                print("初始化设备失败")
                return False
            
            # 连接设备
            if not daq207.connect_device(device_handle):
                print("连接设备失败")
                return False
            time.sleep(1)
            
            # 配置设备参数（与DAQ206相同的配置）
            if not daq207.config_adc_trigger(device_handle, 
                                            DeviceConfig.TRIGGER_TYPE_DOUBLE_EDGE,
                                            DeviceConfig.TRIGGER_MODE_COMMON,
                                            DeviceConfig.TRIGGER_CHANNEL_NONE,
                                            DeviceConfig.TRIGGER_LEVEL):
                print("配置触发失败")
                return False
            
            if not daq207.config_adc_sample_rate(device_handle, DeviceConfig.SAMPLE_RATE_500K):
                print("配置采样率失败")
                return False
            
            if not daq207.config_adc_voltage(device_handle, DeviceConfig.VOLTAGE_10V):
                print("配置电压范围失败")
                return False
            
            # DAQ207是2通道设备
            channel_mask = 0x03
            if not daq207.config_adc_channel(device_handle, channel_mask):
                print("配置ADC通道失败")
                return False
            
            if not daq207.config_adc_trigger_length(device_handle, DeviceConfig.TRIGGER_LENGTH):
                print("配置触发长度失败")
                return False
            
            # 设置全通道DC
            acdc_channel = 0x03  # 全通道DC
            if not daq207.config_acdc(device_handle, acdc_channel):
                print("配置ACDC失败")
                return False

            # 设置超时时间
            if not daq207.config_trigger_timeout(device_handle, 100):
                print("设置超时时间失败")
                return False
            
            # 执行采集流程
            if not daq207.stop_collection(device_handle):
                print("停止采集失败")
                return False
            
            time.sleep(3.0)
            
            if not daq207.start_collection(device_handle):
                print("开始采集失败")
                return False
            
            time.sleep(3.0)
            
            # 软件触发
            if not daq207.config_adc_trigger_source(device_handle):
                print("配置触发源失败")
                return False
            
            # 读取数据
            channel_count = daq207.get_adc_legal_channel_size(device_handle)
            for channel in range(channel_count):
                while True:
                    success, data = daq207.try_read_data_batch(device_handle, channel,
                                                             DeviceConfig.TRIGGER_LENGTH)
                    if not success:
                        continue
                    
                    print(f"成功从通道 {channel + 1} 读取 {len(data)} 个数据点")
                    if data:
                        print(f"通道 {channel + 1} 前10个值: {data[:10]}")
                    break
            
            if not daq207.stop_collection(device_handle):
                print("停止采集失败")
                return False
            
            if not daq207.disconnect_device(device_handle):
                print("断开设备连接失败")
                return False
            
            print("DAQ207测试成功完成")
            return True
            
        finally:
            daq207.delete_device(device_handle)
    
    finally:
        tcp_server.delete_server(server_handle)

def test_daq216():
    """测试DAQ216设备"""
    print("开始测试DAQ216设备")
    
    # 创建TCP服务器
    tcp_server = TCPServerBinding(DLL_PATH)
    server_handle = tcp_server.create_server(DeviceConfig.IP_ADDRESS, DeviceConfig.PORT)
    if not server_handle:
        print("创建TCP服务器失败")
        return False
    
    try:
        # 开始接受连接
        tcp_server.start_accept(server_handle, 10000, True, 1)
        
        # 等待连接完成
        while not tcp_server.is_accept_complete(server_handle):
            time.sleep(0.1)
        
        # 获取客户端列表
        client_ips = tcp_server.get_clients_ip(server_handle)
        print(f"获取到客户端列表，数量: {len(client_ips)}")
        
        if not client_ips:
            print("没有获取到客户端")
            return False
        
        # 获取客户端句柄
        client_handle = tcp_server.get_client(server_handle, client_ips[0])
        if not client_handle:
            print("获取客户端句柄失败")
            return False
        
        # 创建DAQ216设备
        daq216 = DAQ216Binding(DLL_PATH)
        device_handle = daq216.create_device()
        if not device_handle:
            print("创建DAQ216设备失败")
            return False
        
        try:
            # 使用后端
            if not daq216.use_backend(device_handle, client_handle):
                print("设置设备后端失败")
                return False
            
            # 初始化设备
            if not daq216.initialize_device(device_handle):
                print("初始化设备失败")
                return False
            
            # 连接设备
            if not daq216.connect_device(device_handle):
                print("连接设备失败")
                return False
            time.sleep(1)
            
            # 配置设备参数
            if not daq216.config_adc_trigger(device_handle, 
                                            DeviceConfig.TRIGGER_TYPE_DOUBLE_EDGE,
                                            DeviceConfig.TRIGGER_MODE_COMMON,
                                            DeviceConfig.TRIGGER_CHANNEL_NONE,
                                            DeviceConfig.TRIGGER_LEVEL):
                print("配置触发失败")
                return False
            
            if not daq216.config_adc_sample_rate(device_handle, DeviceConfig.SAMPLE_RATE_500K):
                print("配置采样率失败")
                return False
            
            if not daq216.config_adc_voltage(device_handle, DeviceConfig.VOLTAGE_10V):
                print("配置电压范围失败")
                return False
            
            # DAQ216是4通道设备
            channel_mask = 0x0F  # 0b00001111
            if not daq216.config_adc_channel(device_handle, channel_mask):
                print("配置ADC通道失败")
                return False
            
            if not daq216.config_adc_trigger_length(device_handle, DeviceConfig.TRIGGER_LENGTH):
                print("配置触发长度失败")
                return False
            
            # 设置全通道DC
            acdc_channel = 0x0F  # 全通道DC
            if not daq216.config_acdc(device_handle, acdc_channel):
                print("配置ACDC失败")
                return False
            
            # 执行采集流程
            if not daq216.stop_collection(device_handle):
                print("停止采集失败")
                return False
            
            time.sleep(3.0)
            
            if not daq216.start_collection(device_handle):
                print("开始采集失败")
                return False
            
            time.sleep(3.0)
            
            # 软件触发
            if not daq216.config_adc_trigger_source(device_handle):
                print("配置触发源失败")
                return False
            
            # 读取数据
            channel_count = daq216.get_adc_legal_channel_size(device_handle)
            for channel in range(channel_count):
                while True:
                    success, data = daq216.try_read_data_batch(device_handle, channel,
                                                             DeviceConfig.TRIGGER_LENGTH)
                    if not success:
                        continue
                    
                    print(f"成功从通道 {channel + 1} 读取 {len(data)} 个数据点")
                    if data:
                        print(f"通道 {channel + 1} 前10个值: {data[:10]}")
                    break
            
            if not daq216.stop_collection(device_handle):
                print("停止采集失败")
                return False
            
            if not daq216.disconnect_device(device_handle):
                print("断开设备连接失败")
                return False
            
            print("DAQ216测试成功完成")
            return True
            
        finally:
            daq216.delete_device(device_handle)
    
    finally:
        tcp_server.delete_server(server_handle)

def test_daq217():
    """测试DAQ217设备"""
    print("开始测试DAQ217设备")
    
    # 创建TCP服务器
    tcp_server = TCPServerBinding(DLL_PATH)
    server_handle = tcp_server.create_server(DeviceConfig.IP_ADDRESS, DeviceConfig.PORT)
    if not server_handle:
        print("创建TCP服务器失败")
        return False
    
    try:
        # 开始接受连接
        tcp_server.start_accept(server_handle, 10000, True, 1)
        
        # 等待连接完成
        while not tcp_server.is_accept_complete(server_handle):
            time.sleep(0.1)
        
        # 获取客户端列表
        client_ips = tcp_server.get_clients_ip(server_handle)
        print(f"获取到客户端列表，数量: {len(client_ips)}")
        
        if not client_ips:
            print("没有获取到客户端")
            return False
        
        # 获取客户端句柄
        client_handle = tcp_server.get_client(server_handle, client_ips[0])
        if not client_handle:
            print("获取客户端句柄失败")
            return False
        
        # 创建DAQ217设备
        daq217 = DAQ217Binding(DLL_PATH)
        device_handle = daq217.create_device()
        if not device_handle:
            print("创建DAQ217设备失败")
            return False
        
        try:
            # 使用后端
            if not daq217.use_backend(device_handle, client_handle):
                print("设置设备后端失败")
                return False
            
            # 初始化设备
            if not daq217.initialize_device(device_handle):
                print("初始化设备失败")
                return False
            
            # 连接设备
            if not daq217.connect_device(device_handle):
                print("连接设备失败")
                return False

            time.sleep(1)
            
            # 配置设备参数
            if not daq217.config_adc_trigger(device_handle, 
                                            DeviceConfig.TRIGGER_TYPE_DOUBLE_EDGE,
                                            DeviceConfig.TRIGGER_MODE_COMMON,
                                            DeviceConfig.TRIGGER_CHANNEL_NONE,
                                            DeviceConfig.TRIGGER_LEVEL):
                print("配置触发失败")
                return False
            
            if not daq217.config_adc_sample_rate(device_handle, DeviceConfig.SAMPLE_RATE_500K):
                print("配置采样率失败")
                return False
            
            if not daq217.config_adc_voltage(device_handle, DeviceConfig.VOLTAGE_10V):
                print("配置电压范围失败")
                return False
            
            # DAQ217是4通道设备
            channel_mask = 0x0F  # 0b00001111
            if not daq217.config_adc_channel(device_handle, channel_mask):
                print("配置ADC通道失败")
                return False
            
            if not daq217.config_adc_trigger_length(device_handle, DeviceConfig.TRIGGER_LENGTH):
                print("配置触发长度失败")
                return False
            
            # 设置全通道DC
            acdc_channel = 0x0F  # 全通道DC
            if not daq217.config_acdc(device_handle, acdc_channel):
                print("配置ACDC失败")
                return False
            
            # 执行采集流程
            if not daq217.stop_collection(device_handle):
                print("停止采集失败")
                return False
            
            time.sleep(3.0)
            
            if not daq217.start_collection(device_handle):
                print("开始采集失败")
                return False
            
            time.sleep(3.0)
            
            # 软件触发
            if not daq217.config_adc_trigger_source(device_handle):
                print("配置触发源失败")
                return False
            
            # 读取数据
            channel_count = daq217.get_adc_legal_channel_size(device_handle)
            for channel in range(channel_count):
                while True:
                    success, data = daq217.try_read_data_batch(device_handle, channel,
                                                             DeviceConfig.TRIGGER_LENGTH)
                    if not success:
                        continue
                    
                    print(f"成功从通道 {channel + 1} 读取 {len(data)} 个数据点")
                    if data:
                        print(f"通道 {channel + 1} 前10个值: {data[:10]}")
                    break
            
            if not daq217.stop_collection(device_handle):
                print("停止采集失败")
                return False
            
            if not daq217.disconnect_device(device_handle):
                print("断开设备连接失败")
                return False
            
            print("DAQ217测试成功完成")
            return True
            
        finally:
            daq217.delete_device(device_handle)
    
    finally:
        tcp_server.delete_server(server_handle)

def test_daq322():
    """测试DAQ322设备 - 滚动模式，采样率200k，持续采集"""
    print("开始测试DAQ322设备 - 滚动模式")
    
    # 创建TCP服务器
    tcp_server = TCPServerBinding(DLL_PATH)
    server_handle = tcp_server.create_server(DeviceConfig.IP_ADDRESS, DeviceConfig.PORT)
    if not server_handle:
        print("创建TCP服务器失败")
        return False
    
    try:
        # 开始接受连接
        tcp_server.start_accept(server_handle, 10000, True, 1)
        
        # 等待连接完成
        while not tcp_server.is_accept_complete(server_handle):
            time.sleep(0.1)
        
        # 获取客户端列表
        client_ips = tcp_server.get_clients_ip(server_handle)
        print(f"获取到客户端列表，数量: {len(client_ips)}")
        
        if not client_ips:
            print("没有获取到客户端")
            return False
        
        # 获取客户端句柄
        client_handle = tcp_server.get_client(server_handle, client_ips[0])
        if not client_handle:
            print("获取客户端句柄失败")
            return False
        
        print("成功获取客户端句柄")
        
        # 创建DAQ322设备
        daq322 = DAQ322Binding(DLL_PATH)
        device_handle = daq322.create_device()
        if not device_handle:
            print("创建DAQ322设备失败")
            return False
        
        try:
            # 使用后端
            if not daq322.use_backend(device_handle, client_handle):
                print("设置设备后端失败")
                return False
            
            # 初始化设备
            if not daq322.initialize_device(device_handle):
                print("初始化设备失败")
                return False
            
            # 连接设备
            if not daq322.connect_device(device_handle):
                print("连接设备失败")
                return False
            time.sleep(1)
            
            # 配置ADC触发 - 滚动模式（无触发）
            # 使用Normal触发类型表示滚动模式
            from python_bind.base_device_binding import LockzhinerADCTriggerType, LockzhinerADCTriggerMode
            ROLLING_TRIGGER_TYPE = LockzhinerADCTriggerType.Normal
            ROLLING_TRIGGER_MODE = LockzhinerADCTriggerMode.Automatic
            
            if not daq322.config_adc_trigger(device_handle, 
                                           ROLLING_TRIGGER_TYPE,
                                           ROLLING_TRIGGER_MODE,
                                           DeviceConfig.TRIGGER_CHANNEL_NONE,
                                           DeviceConfig.TRIGGER_LEVEL):
                print("配置触发失败")
                return False
            
            # 设置采样率200k
            from python_bind.base_device_binding import LockzhinerADCSampleRate
            SAMPLE_RATE_200K = LockzhinerADCSampleRate.ADCSampleRate_200_K
            if not daq322.config_adc_sample_rate(device_handle, SAMPLE_RATE_200K):
                print("配置采样率失败")
                return False
            
            # 电压范围±10V
            if not daq322.config_adc_voltage(device_handle, DeviceConfig.VOLTAGE_10V):
                print("配置电压范围失败")
                return False
            
            # 设置开启8通道 (DAQ322是8通道设备)
            channel_mask = 0xFF
            if not daq322.config_adc_channel(device_handle, channel_mask):
                print("配置ADC通道失败")
                return False
            
            # 设置采集长度4920
            if not daq322.config_adc_trigger_length(device_handle, DeviceConfig.TRIGGER_LENGTH):
                print("配置触发长度失败")
                return False
            
            # 设置全通道DC (1代表DC，0代表AC)
            acdc_channel = 0xFF  # 全通道DC
            if not daq322.config_acdc(device_handle, acdc_channel):
                print("配置ACDC失败")
                return False
            
            # 停止上次采集
            if not daq322.stop_collection(device_handle):
                print("停止采集失败")
                return False
            
            # 等待3秒
            time.sleep(3.0)
            
            # 开始采集
            if not daq322.start_collection(device_handle):
                print("开始采集失败")
                return False
            
            print("DAQ322开始滚动模式采集，按Ctrl+C停止...")
            
            # 持续读取数据，直到用户按Ctrl+C
            try:
                channel_count = daq322.get_adc_legal_channel_size(device_handle)
                read_count = 0
                
                while True:
                    for channel in range(channel_count):
                        success, data = daq322.try_read_data_batch(device_handle, channel, 
                                                                 DeviceConfig.TRIGGER_LENGTH)
                        if not success:
                            continue
                        
                        read_count += 1
                        print(f"第{read_count}次读取 - 通道 {channel + 1}: {len(data)} 个数据点")
                        
                        # 输出前10个值
                        if data and len(data) > 0:
                            print(f"通道 {channel + 1} 前10个值: {data[:10]}")
                    
                    # 短暂延时，避免CPU占用过高
                    time.sleep(0.1)
                    
            except KeyboardInterrupt:
                print("\n用户中断采集")
            
            # 停止采集
            if not daq322.stop_collection(device_handle):
                print("停止采集失败")
                return False
            
            # 断开设备连接
            if not daq322.disconnect_device(device_handle):
                print("断开设备连接失败")
                return False
            
            print("DAQ322测试成功完成")
            return True
            
        finally:
            # 清理设备资源
            daq322.delete_device(device_handle)
    
    finally:
        # 清理TCP服务器资源
        tcp_server.delete_server(server_handle)

# 测试函数调用
# 如需测试其他设备，请修改此处的函数调用
if __name__ == "__main__":
    print("DAQ设备TCP连接测试程序 - Python版本")
    
    # 只允许调用一个设备测试函数，通过人为控制
    # result = test_daq217()
    # result = test_daq206()
    result = test_daq207()
    # result = test_daq216()
    # result = test_daq322()

    if result:
        print("设备测试成功完成")
    else:
        print("设备测试失败")
